package com.clicacao.clicacao;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

import com.clicacao.library.ClicacaoFunctions;
import com.clicacao.library.DatabaseHandler;

public class UserItensScreen extends Activity{
	
	HashMap<String, String> usuario;
	ListView listView;
	Context context;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_itens_screen);
		
		//Pegando o id da mochila
		usuario = new HashMap<String, String>();
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		usuario = db.getUserDetails();
		
		//Salvando o contexto atual do sistema
		context = this;
		
		//Inicializando o listview
		listView = (ListView)findViewById(R.id.lsvItensUsuario);
		
		new AsyncTask<Void, Void, JSONObject>(){
			
			ClicacaoFunctions clicacaoFunctions;
			String umid = usuario.get("id_mochila");
			ArrayList<HashMap<String, String>> objectlist;
			HashMap<String, String> object;
			
			@Override
			protected JSONObject doInBackground(Void... params) {
				JSONObject json;
				clicacaoFunctions = new ClicacaoFunctions();
				json = clicacaoFunctions.getUserBagObjects(umid);
				return json;
			}
			
			@Override
			protected void onPostExecute(JSONObject result) {
				super.onPostExecute(result);
				//Acabo com a mensagem de carregando
				//Com a resposta json obtida, fazemos o parser para preencher o listview
				try {
					//Confere para ver se o resultado foi positivo
					objectlist = new ArrayList<HashMap<String,String>>();
					if(result.getString("success").equals("1")){
						JSONArray json_objects_array = result.getJSONArray("objeto");
						if(json_objects_array.isNull(0)){
							//Nao encontrou nenhum objeto para o usuario
							Toast.makeText(getApplicationContext(), "Usuario nao possui nenhum OBJETO em sua mochila!", Toast.LENGTH_SHORT).show();
						}else{//Preenche o listview
							Integer i = Integer.valueOf(0);
							for(i = 0; i < json_objects_array.length(); i++){
								object = new HashMap<String, String>();
								JSONObject json_object = json_objects_array.getJSONObject(i);
								//upi.put("upiid", json_upi.getString("upiid"));
								object.put("tipo_objeto", json_object.getString("tipo_objeto"));
								object.put("nome", json_object.getString("nome"));
								object.put("dono", json_object.getString("id_usuario"));
								object.put("_id", json_object.getString("oid"));
								objectlist.add(object);
							}
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//Hora de preencher o listview
				//Primeiro confere para ver se objectlist nao esta vazio
				if(!objectlist.isEmpty()){
					String campos[] = {"_id", "dono", "nome", "tipo_objeto"};
					int layout[] = {R.id.tvIdObject,
									R.id.tvTipoObject, 
									R.id.tvNomeObject, 
									R.id.tvIdUser};
					
					ListAdapter listAdapter = new SimpleAdapter(getApplicationContext(), 
																	objectlist, 
																	R.layout.adventure_bag_object_row, 
																	campos, 
																	layout);
					
					try{
						listView.setAdapter(listAdapter);
					}catch(Exception e){
						e.printStackTrace();
					}
					
					listView.setLongClickable(true);
					listView.setOnItemLongClickListener(new OnItemLongClickListener() {

						public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
							//Aqui vou visualizar a UPI que esta na lista
							//final AdapterView<?> av = parent;
							//final int positionToDrop = position; 
							
							AlertDialog.Builder adb = new AlertDialog.Builder(context);
							//Log.e("DIALOG", "TESTE");
							adb.setTitle("Guardar OBJETO no CONTAINER");
							adb.setMessage("Guardar OBJETO no container?");
							adb.setNegativeButton("Nao", null);
							adb.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									
									/*
									//Toast.makeText(getApplicationContext(), "Dropar UPI " + id1, Toast.LENGTH_SHORT).show();
									HashMap<String, String> lista = new HashMap<String, String>();
									lista = (HashMap<String, String>)av.getItemAtPosition(positionToDrop);
									final String objectid = lista.get("_id").toString();
									//Mudando parametros para representar que larguei a UPI na aventura
									//Para isto preciso de uma thread assincrona
									new AsyncTask<Void, Void, JSONObject>(){
										
										ClicacaoFunctions clicacaoFunctions;
										
										@Override
										protected JSONObject doInBackground(
												Void... params) {
											clicacaoFunctions = new ClicacaoFunctions();
											JSONObject json = clicacaoFunctions.dropObjectToAdventure(objectid, aid, latitude, longitude);
											return json;
										}

										@Override
										protected void onPostExecute(
												JSONObject result) {
											//Analisa o JSON para ver se a operacao foi bem sucedida
											super.onPostExecute(result);
											
											try{
												if(result.getString("success").equalsIgnoreCase("1")){
													Toast.makeText(getApplicationContext(), "O OBJETO foi largado no mapa com sucesso!", Toast.LENGTH_SHORT).show();
												}else{
													Toast.makeText(getApplicationContext(), "Nao foi possivel largar o OBJETO!", Toast.LENGTH_SHORT).show();
												}
											}catch(JSONException e){
												e.printStackTrace();
											}
											
											onDestroy();
											
										}
										
									}.execute();
								*/
								}
							});
							adb.show();
							
							return false;
						}
					
					});
					
					listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

						public void onItemClick(AdapterView<?> parent, View view,
								int position, long id) {

							//Toast.makeText(getApplicationContext(), "UPI " + parent.getItemIdAtPosition(position), Toast.LENGTH_SHORT).show();
						}
				
					});
				}
			}
		}.execute();
		
	}

}
